package com.xinshujia.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.xinshujia.entity.UserEntity;
import com.xinshujia.service.UserService;
import com.xinshujia.utils.GsonUtil;
import com.xinshujia.utils.response.RespResult;
import org.springframework.web.bind.annotation.*;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-15 19:38       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 * 用户控制器
 */
@RestController
@RequestMapping("user")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 新增用户
     */
    @PostMapping("insert")
    public RespResult insert(@RequestBody UserEntity userEntity) {
        boolean flag = userService.insert(userEntity);
        if (flag) {
            return RespResult.OK();
        } else {
            return RespResult.Fail();
        }
    }

    /**
     * 根据Id删除用户（实际是更新操作）
     */
    @DeleteMapping("deleteById/{id}")
    public RespResult deleteById(@PathVariable("id") Long id) {
        boolean flag = userService.deleteById(id);
        if (flag) {
            return RespResult.OK();
        } else {
            return RespResult.Fail();
        }
    }

    /*全量更新*/
    @PutMapping("update")
    public RespResult updateUser(@RequestBody UserEntity userEntity) {
        boolean flag = userService.updateById(userEntity);
        if (flag) {
            return RespResult.OK();
        } else {
            return RespResult.Fail();
        }
    }

    /*单个属性更新*/
    @GetMapping("patch")
    public RespResult patchUser(@RequestParam("id") Long id, @RequestParam("enabled") int enabled) {
        System.out.println("id:" + id + " enabled:" + enabled);
        boolean flag = userService.patchUser(id, enabled);
        if (flag) {
            return RespResult.OK();
        } else {
            return RespResult.Fail();
        }
    }

    /**
     * 分页查询
     */
    @GetMapping("getUsersByPage")
    public RespResult findAllByPage(@RequestParam("pageSize") Long pageSize,
                                    @RequestParam("pageNum") Long pageNum,
                                    @RequestParam("username") String username) {
        Page<UserEntity> allByPage = userService.findAllByPage(pageNum, pageSize, username);
        Gson gson = GsonUtil.googleGson();
        return RespResult.OK(gson.toJson(allByPage));
    }

    @GetMapping("getUserById/{id}")
    public RespResult getUserById(@PathVariable("id") Long id) {
        UserEntity userEntity = userService.getById(id);
        if (userEntity != null) {
            return RespResult.OK(userEntity);
        } else {
            return RespResult.Fail();
        }
    }

}
